package cn.gayaguoguo.guohealthindicator.listener;

import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.scheduler.BukkitRunnable;

import cn.gayaguoguo.guohealthindicator.GuoHealthIndicator;

public class AttackListener implements Listener{
	
	private GuoHealthIndicator plugin;

	public AttackListener(GuoHealthIndicator plugin) {
		this.plugin = plugin;
	}
	
	@EventHandler
	public void onEntityDamageByEntity(EntityDamageByEntityEvent e){
		if (!(e.getEntity() instanceof LivingEntity)){
			return;
		}
		Player player = null;
		Entity damager = e.getDamager();
		if (damager instanceof Player) {
			player = (Player) damager;
		}
		if (damager instanceof Projectile) {
			if (((Projectile) damager).getShooter() instanceof Player) {
				player = (Player) ((Projectile) damager).getShooter();
			}
		}
		if (damager instanceof TNTPrimed) {
			if (((TNTPrimed) damager).getSource() instanceof Player) {
				player = (Player) ((TNTPrimed) damager).getSource();
			}
		}
		if (player == null) {
			return;
		}
		String playerName = player.getName();
		new BukkitRunnable() {
			
			@Override
			public void run() {

				plugin.getHealthBarManager().addLink(playerName, (LivingEntity) e.getEntity());
				
			}
		}.runTaskAsynchronously(plugin);
	}
	
	@EventHandler
	public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent e){
		if (!(e.getRightClicked() instanceof LivingEntity)){
			return;
		}
		new BukkitRunnable() {
			
			@Override
			public void run() {

				plugin.getHealthBarManager().addLink(e.getPlayer().getName(), (LivingEntity) e.getRightClicked());
				
			}
		}.runTaskAsynchronously(plugin);
	}
}
